package logic

import (
	"context"
	"errors"
	"strconv"
	"video-guard/models/cache"
	"video-guard/models/mysql"
	"video-guard/pkg"

	"video-guard/videorpc/internal/svc"
	"video-guard/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *videorpc.LoginRequest) (*videorpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.UserInfo

	err := user.FirstUserByMobile(mysql.DB, in.Mobile)
	if err != nil {
		return nil, errors.New("该用户不存在")
	}

	if user.AccountStatus == 1 {
		return nil, errors.New("账号已禁用，请联系管理员")
	}

	if in.LoginType == 0 {

		result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()

		if result != in.SmsCode {
			return nil, errors.New("验证码错误")
		}

	} else if in.LoginType == 1 {

		if user.Pwd != pkg.Md5(in.Password) {
			return nil, errors.New("密码错误")
		}

	}

	handler, err := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	if err != nil {
		return nil, err
	}

	return &videorpc.LoginResponse{
		UserId: handler,
	}, nil
}
